//
//  UserDetailController.swift
//  用户详情界面
//
//  Created by smile on 2019/6/14.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//用户详情头部视图
import JXPagingView

//指示器
import JXCategoryView

class UserDetailController: BaseTitleController {
    
    /// 内容容器
    @IBOutlet weak var contentContainer: UIView!
    
    /// 用户详情头部View
    var userDetailHeaderView:UserDetailHeaderView!
    
    /// 用户详情歌单View
    var userDetailSheetView:UserDetailSheetView!
    
    /// 用户详情动态流View
    var userDetailFeedView:UserDetailFeedView!
    
    /// 用户详情关于我View
    var userDetailAboutView:UserDetailAboutView!
    
    /// 指示器View
    var indicatorView:JXCategoryTitleView!
    
    /// 该界面整体的View
    var pageView:JXPagingListRefreshView!
    
    /// 用户Id
    var userId:String?
    
    /// 昵称
    var nickname:String?
    
    /// 列表数据源
    var listViewArray:[JXPagingViewListViewDelegate]!
    
    
    override func initViews() {
        super.initViews()
        
        setTitle("用户详情")
        
        //获取屏幕宽度
        let width = UIScreen.main.bounds.width
        
        //创建header
        userDetailHeaderView=UserDetailHeaderView(frame: CGRect(x: 0, y: 0, width: width, height: SIZE_HEADER_HEIGHT))
        
        //设置关注按钮点击回调
        userDetailHeaderView.onFollowClick = {
            data in
            self.onFollowClick(data)
        }
        
        //设置发送消息按钮点击回调方法
        userDetailHeaderView.onSendMessageClick={
            data in
            self.onSendMessageClick(data)
        }
        
        //创建三个要显示的View
        //创建用户详情歌单View
        userDetailSheetView = UserDetailSheetView()
        
        //设置歌单点击回调方法
        userDetailSheetView.onSheetClick={
            data in
            SheetDetailController.start(self.navigationController!, data.id)
        }
        
        //创建用户详情动态流View
        userDetailFeedView=UserDetailFeedView()
        
        //创建用户详情关于我View
        userDetailAboutView=UserDetailAboutView()
        
        //放到列表中
        listViewArray=[userDetailSheetView,userDetailFeedView,userDetailAboutView] as! [JXPagingViewListViewDelegate]
        
        //指示器
        indicatorView=JXCategoryTitleView(frame: CGRect(x: 0, y: 0, width: width, height: SIZE_INDICATOR_HEIGHT))
        
        //设置代理
        indicatorView.delegate=self
        
        //设置指示器标题
        indicatorView.titles=["音乐","动态","关于"]
        
        //背景颜色
        indicatorView.backgroundColor=UIColor.white
        
        //默认颜色
        indicatorView.titleColor=UIColor.black
        
        //选择后的标题颜色
        indicatorView.titleSelectedColor=UIColor(hex: COLOR_PRIMARY)
        
        //选中后标题缩放
        indicatorView.titleLabelZoomEnabled=false
        
        //颜色是否渐变过度
        indicatorView.titleColorGradientEnabled=true
        
        //创建指示器线
        let lineView = JXCategoryIndicatorLineView.init()
        
        //颜色
        lineView.indicatorLineViewColor=UIColor(hex: COLOR_PRIMARY)
        
        //设置宽度
        lineView.indicatorLineWidth=60
        
        //设置指示器先到指示器控件
        indicatorView.indicators=[lineView]
        
        //创建下拉刷新View
        pageView=JXPagingListRefreshView(delegate: self)
        
        //设置手势识别器代理
        pageView.mainTableView.gestureDelegate=self
        
        //添加到布局
        contentContainer.addSubview(pageView)
        
        //设置指示器
        indicatorView.contentScrollView=pageView.listContainerView.collectionView
        
        //添加手势识别器
        pageView.listContainerView.collectionView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pageView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)

    }
    
    /// 发送消息按钮点击回调
    ///
    /// - Parameter data: <#data description#>
    func onSendMessageClick(_ data:User) {
        ChatController.start(navigationController!, StringUtil.wrapperUserId(data.id))
    }
    
    /// 关注按钮点击回调
    ///
    /// - Parameter data: <#data description#>
    func onFollowClick(_ data:User) {
        if data.isFollowing() {
            //已经关注了
            
            //取消关注
            Api.shared.deleteFollow(data.id).subscribeOnSuccess { (_) in
                //取消关注成功
                data.following=nil
                
                //刷新关注状态
                self.userDetailHeaderView.showFollowStatus()
            }.disposed(by: disposeBag)
        } else {
            //没有关注
            
            //关注
            Api.shared.follow(data.id).subscribeOnSuccess { (_) in
                //关注成功
                data.following=1
                
                //刷新关注状态
                self.userDetailHeaderView.showFollowStatus()
            }.disposed(by: disposeBag)
        }
    }
    
    override func viewDidLayoutSubviews() {
        //重新设置pageView的尺寸和位置
        pageView.frame=contentContainer.bounds
    }

    override func initDatas() {
        super.initDatas()
        
        //先根据id获取
        if let userId = userId {
            //根据id获取
            getUserDetail(userId,nil)
        }else if let nickname = nickname {
            //根据昵称获取
            getUserDetail("-1",nickname)
        }else {
            //TODO 错误处理
        }
    }
    
    /// 获取用户详情
    ///
    /// - Parameters:
    ///   - id: <#id description#>
    ///   - nickname: <#nickname description#>
    func getUserDetail(_ id:String!,_ nickname:String?) {
        Api.shared.userDetail(id: id, nickname: nickname).subscribeOnSuccess { (data) in
            if let data = data?.data {
                self.showData(data)
            }
        }.disposed(by: disposeBag)
    }
    
    /// 显示数据
    ///
    /// - Parameter data: <#data description#>
    func showData(_ data:User) {
        print("UserDetailController showData:\(data.nickname)")
        
        //显示header数据
        userDetailHeaderView.bindData(data)
        
        userDetailSheetView.userId=data.id
        userDetailSheetView.customInit()
        
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: - 启动方法
extension UserDetailController {
    
    /// 根据用户Id获取用户详情
    ///
    /// - Parameters:
    ///   - navigationController: <#navigationController description#>
    ///   - userId: <#userId description#>
    static func start(_ navigationController:UINavigationController,userId:String) {
        
        //创建Storyboard
        let storyboard=UIStoryboard(name: "Main", bundle: nil)
        
        //创建Controller
        let controller = storyboard.instantiateViewController(withIdentifier: "UserDetail") as! UserDetailController
        
        //传递参数
        controller.userId = userId
        
        //将控制器压入导航控制器
        navigationController.pushViewController(controller, animated: true)
    }
    
    /// 根据用户昵称获取用户详情
    ///
    /// - Parameters:
    ///   - navigationController: <#navigationController description#>
    ///   - nickname: <#nickname description#>
    static func start(_ navigationController:UINavigationController, nickname:String) {
        //创建控制器
        let controller = navigationController.storyboard!.instantiateViewController(withIdentifier: "UserDetail") as! UserDetailController
        
        //传递参数
        controller.nickname = nickname
        
        //将控制器压入导航栏控制器
        navigationController.pushViewController(controller, animated: true)
    }
}

// MARK: - PageView代理
//该代理的主要作用是，告诉PageView控件，有多少个页面，每个页面对应的View。
extension UserDetailController:JXPagingViewDelegate {
    
    /// 返回头部View的高度
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return Int(SIZE_HEADER_HEIGHT)
    }
    
    /// 返回头部View
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userDetailHeaderView
    }
    
    /// 指示器高度
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return Int(SIZE_INDICATOR_HEIGHT)
    }
    
    /// 返回指示器View
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return indicatorView
    }
    
    /// 有多少个界面
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return listViewArray.count
    }
    
    /// 返回对应位置的View
    ///
    /// - Parameters:
    ///   - pagingView: <#pagingView description#>
    ///   - index: <#index description#>
    /// - Returns: <#return value description#>
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        return listViewArray[index]
    }
}

// MARK: - 指示器代理
extension UserDetailController:JXCategoryViewDelegate{
    /// 点击选中或者滚动选中都会调用该方法
    /// 适用于只关心选中事件
    /// 不关心具体是点击还是滚动选中的
    func categoryView(_ categoryView: JXCategoryBaseView!, didSelectedItemAt index: Int) {
        navigationController?.interactivePopGestureRecognizer?.isEnabled==(index == 0)
    }
    
    /// 只有点击的时候调用
    ///
    /// - Parameters:
    ///   - categoryView: <#categoryView description#>
    ///   - index: <#index description#>
    func categoryView(_ categoryView: JXCategoryBaseView!, didClickedItemContentScrollViewTransitionTo index: Int) {
        //滚动到对应位置的View
        pageView.listContainerView.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false)
    }
}

// MARK: - JXPagingMainTableView手势代理
extension UserDetailController: JXPagingMainTableViewGestureDelegate{
    /// 主要是处理滑动冲突
    /// 如果headerView（或其他地方）有水平滚动的scrollView
    /// 当其正在左右滑动的时候
    /// 就不能让列表上下滑动
    /// 所以有此代理方法进行对应处理
    ///
    /// - Parameters:
    ///   - gestureRecognizer: <#gestureRecognizer description#>
    ///   - otherGestureRecognizer: <#otherGestureRecognizer description#>
    /// - Returns: <#return value description#>
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止categoryView左右滑动的时候
        //上下和左右都可以滚动
        if otherGestureRecognizer == indicatorView?.collectionView.panGestureRecognizer {
            return false
        }
        
        //手势识别器判断
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder())
    }
}
